/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package karelia.webpro.controllers;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import karelia.webpro.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

/**
 *
 * @author edu100
 */
@Controller
@SessionAttributes
public class RegisterController {
    
    static final String USER = "webprojaa@gmail.com";
    static final int PORT = 465;
    static final String HOST = "smtp.google.com";
    
    final String USERNAME = "webprojaa";
    final String PASSWORD = "arijaarttu";

    
    @RequestMapping(value="register")
    public void register(){
        
    }
    
    @RequestMapping(value = "/registerConfirm", method = RequestMethod.POST)
    public void registerUser( @RequestParam(value="email", required=true) String email,
                        @RequestParam(value="password", required=true) String password){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("web-ohj-proj-aaPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        User user = new User(email,password,false);
        em.persist(user);
        em.getTransaction().commit();
        em.close();
        emf.close();
        sendMail(email);
        System.out.println(email + "." + password);    
    }

    
public void sendMail(String email){
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
    
    Session session = Session.getInstance(props,
        new javax.mail.Authenticator() {
	protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USERNAME, PASSWORD);
	}
    });
    try
        {     
 			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(USER));
			message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(email));
			message.setSubject("Confirm email");
			message.setText("sun linkki");
			Transport.send(message);
			System.out.println("Done");
 
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
